package file;

import it.sauronsoftware.jave.Encoder;
import org.apache.log4j.Logger;
import utils.VideoCutUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.channels.FileChannel;

/**
 * @author：xingquanxiang createTime:2020/4/27 14:15
 * description:
 * Main-Class: file.FileStatistics
 */
public class FileStatistics {
    private static Logger logger = Logger.getLogger(FileStatistics.class);
    //片头文件
    private final  File headVideo = new File("F:\\head.ts");
    //匹配盘符子目录
    private final String regex = "老鹰";
    //替换盘符子目录
    private final String replacement = "老鹰合成";
    //合成输出视频前缀
    private final String destVideoPrefix = "LH_";

    public static int count = 0;
    public static long totalTime = 0;
    public static long totalSize = 0;
    public static long totalL = 0;
    // VideoCutUtil videoCutUtil = new VideoCutUtil();


    /**
     * 遍历文件 时长大于30分钟的视频 进行切割
     * @param file
     */
    public void traverseCutVideo(File file) {
        if (file.isDirectory()) {
            logger.info(file.getAbsolutePath());
            File[] files = file.listFiles();
            logger.info("文件个数：" + files.length);
            for (File f : files) {
                traverseCutVideo(f);
            }
        } else {
            //判断是否为视频文件
            if (file.getName().endsWith(".mp4") || file.getName().endsWith(".MP4") || file.getName().endsWith(".MOV") || file.getName().endsWith(".mov") || file.getName().endsWith(".MTS") || file.getName().endsWith(".mts")) {
                count++;
                logger.info("" + file.getName());
                long timeLength = getDetails(file);
                if (timeLength>1000*60*30){
                    //执行切割视频
                    VideoCutUtil.cutVideo(file, getDestDirectory(file), timeLength);
                }
            }
        }
    }

    /**
     * 遍历文件添加片头 合成视频
     * @param file
     */
    public void traverseSpliceVideo(File file) {
        if (file.isDirectory()) {
            logger.info(file.getAbsolutePath());
            File[] files = file.listFiles();
            logger.info("文件个数：" + files.length);
            for (File f : files) {
                traverseSpliceVideo(f);
            }
        } else {
            //判断是否为视频文件
            if (file.getName().endsWith(".mp4") || file.getName().endsWith(".MP4") || file.getName().endsWith(".MOV") || file.getName().endsWith(".mov") || file.getName().endsWith(".MTS") || file.getName().endsWith(".mts")) {
                count++;
                long timeLength = getDetails(file);
                if (timeLength>1000*60*30){

                }else{
                    if (file.getName().endsWith(".mp4") || file.getName().endsWith(".MP4")){
                        executeSpliceVideo(file);
                    }else{
                        logger.info("未拼接视频："+file.getAbsolutePath());
                    }
                }
            }
        }
    }


    private void executeSpliceVideo(File resourceVideo){
        //资源视频绝对路径
        String absolutePath = resourceVideo.getAbsolutePath();
        //定义资源视频解码文件路径
        String substring = absolutePath.substring(0, absolutePath.length() - 4);
        String resourceDecodingPath = substring + ".ts";
        //定义合成输出视频路径
        File destVideo = new File(resourceVideo.getParent().replaceFirst(regex, replacement) + "\\"+ destVideoPrefix + resourceVideo.getName());
        if (destVideo.exists()) {
            logger.info("合成输出视频已存在：" + destVideo.getAbsolutePath());
            return;
        }
        //获取合成输出视频父目录
        File destDirectory = destVideo.getParentFile();
        //判断目录是否存在
        if(!destDirectory.exists()&&!destDirectory.isDirectory()) {
            //不存在 创建目录
            destDirectory.mkdirs();
        }
        //执行解码资源视频
        File decodingFile = VideoCutUtil.decodingVideo(resourceVideo, resourceDecodingPath);
        //执行合成视频
        VideoCutUtil.spliceVideo(headVideo, decodingFile, destVideo);
        //删除解码视频
        if (decodingFile.delete()) {
            logger.info("解码视频："+decodingFile.getAbsolutePath()+"删除成功！");
        }
    }


    /**
     * 获取视频详情信息
     *
     * @param source
     * @return 渲染次数
     */
    public long getDetails(File source) {
        Encoder encoder = new Encoder();
        FileChannel fc = null;
        BigDecimal size = null;
        long arg = 0;
        long ls = 0;
        try {
            it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(source);
            ls = m.getDuration();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(source.getName());
            stringBuilder.append("   时长:" + ls / 60000 + "分" + (ls % 60000) / 1000 + "秒！");
            totalTime += ls;
            stringBuilder.append("      格式:" + m.getFormat());
            FileInputStream fis = new FileInputStream(source);
            fc = fis.getChannel();
            final long _size = fc.size();
            totalSize += _size;
            BigDecimal fileSize = new BigDecimal(fc.size());
            size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP);
            stringBuilder.append("      大小" + size + "MB");
            logger.info(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("出现异常："+e.toString());
        } finally {
            System.out.println();
            if (null != fc) {
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ls;
    }

    private File getDestDirectory(File resource) {
        String parent = resource.getParent();
        String resourceName = resource.getName();
        File directory = new File(parent + "\\" + resourceName.substring(0, resourceName.indexOf('.')));
        logger.info(directory.getAbsolutePath());
        if (!directory.exists()) {
            if (directory.mkdir()) {
                logger.info("创建文件夹成功：" + directory.getAbsolutePath());
            } else {
                logger.info("创建文件夹失败：" + directory.getAbsolutePath());
            }
        }
        return directory;
    }
}
